import { ref, defineComponent, getCurrentInstance, onMounted } from 'vue'
import { SelectParams } from '@/components/base/form-item/props/form-item-params'
import AreaSelect, { UpdateSelect } from './area-select'
import { BasePage } from '@/entity/base-model'
/**
 * 省市区联动
 */
export interface AreaProps {
  // 接口api
  action: Function
  // 表单项的参数
  params: SelectParams
  // 区域类型值
  typeValue: AreaTypeValue
}

/**
 * 区域参数
 */
export interface AreaTypeValue {
  // 第一个选择框的初始化参数 todo 根据接口来选择设置
  firstParams?: BasePage
  // 父属性名称
  parentKey: string
  // 子属性名称
  childrenKey: string
}
const App = defineComponent({
  inheritAttrs: false,
  props: {
    // 请求方法
    action: {
      required: true,
      type: Function,
    },
    // 表单项配置参数
    params: {
      type: Object,
      default: () => {},
    },
    // 数据值（v-model）
    value: {
      required: true,
      type: Array,
      validator: (val: Array<string>) => val.length == 3,
    },
    // 区域参数
    typeValue: {
      required: true,
      type: Object,
      default: () => {},
    },
  },
  // 最终返回的数据,数组
  emits: ['update:value'],
  setup(_props, { slots, emit, expose, attrs }) {
    const { action, params, value, typeValue } = _props
    onMounted(() => {
      refsList.value = getCurrentInstance()?.refs
    })
    const refsList = ref()
    // 全局更新方法
    function handlerGlobalUpdate(data: UpdateSelect) {
      const { order, option } = data
      const { childrenKey, parentKey } = typeValue as AreaTypeValue
      // 封装请求参数
      let params = {} as any
      params[childrenKey] = option[parentKey]
      // 切换业务
      switch (order) {
        case 0:
          refsList.value.AreaSelectLevel2.updateData(params)
          value[1] = ''
          value[2] = ''
          refsList.value.AreaSelectLevel2.val = ''
          refsList.value.AreaSelectLevel3.val = ''
          break
        case 1:
          refsList.value.AreaSelectLevel3.updateData(params)
          refsList.value.AreaSelectLevel3.val = ''
          value[2] = ''
          break
      }
    }
    return () => (
      <>
        <AreaSelect
          ref="AreaSelectLevel1"
          action={action}
          params={params}
          order={0}
          v-model:value={value[0]}
          onGlobalUpdate={handlerGlobalUpdate}
          typeValue={typeValue}
        />
        <AreaSelect
          action={action}
          params={params}
          order={1}
          ref="AreaSelectLevel2"
          v-model:value={value[1]}
          onGlobalUpdate={handlerGlobalUpdate}
          typeValue={typeValue}
        />
        <AreaSelect
          action={action}
          params={params}
          order={2}
          ref="AreaSelectLevel3"
          v-model:value={value[2]}
          onGlobalUpdate={handlerGlobalUpdate}
          typeValue={typeValue}
        />
      </>
    )
  },
})

export default App
